﻿using System;
using System.Data;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using InvoiceChecking.Data;
using InvoiceChecking.Entities;
using InvoiceChecking.Web.UI;

public partial class PaymentEdit : Page
{
    public bool IsEditable = true;
    protected void Page_Load(object sender, EventArgs e)
    {
        FormUtilBase.RedirectAfterInsertUpdate(FormView1, "PaymentEdit.aspx?{0}", PaymentDataSource);
        FormUtilBase.RedirectAfterAddNew(FormView1, "PaymentEdit.aspx");
        FormUtilBase.RedirectAfterCancel(FormView1, "Payment.aspx");
        FormUtilBase.SetDefaultMode(FormView1, "PaymentId");

        if (!IsPostBack)
        {
            var dataSet = DataRepository.SunAccountCodeProvider.GetList();
            dataAccountCode.DataSource = dataSet.Tables[0];
            dataAccountCode.DataBind();
            var tcodes = DataRepository.Provider.ExecuteDataSet("_TCode_GetList");
            dataT0.DataSource = tcodes.Tables[0].Select("Tcode='T0'").CopyToDataTable(); dataT0.DataBind();
            dataT1.DataSource = tcodes.Tables[0].Select("Tcode='T1'").CopyToDataTable(); dataT1.DataBind();
            dataT2.DataSource = tcodes.Tables[0].Select("Tcode='T2'").CopyToDataTable(); dataT2.DataBind();
            dataT3.DataSource = tcodes.Tables[0].Select("Tcode='T3'").CopyToDataTable(); dataT3.DataBind();
            if (Request.QueryString["Message"] != null)
            {
                string script = string.Format("openDialog('{0}');",Request.QueryString["Message"]);
                Page.ClientScript.RegisterStartupScript(GetType(),"welcome",script,true);
            }
        }
    }

    protected void FormView1_Load(object sender, EventArgs e)
    {
        var dataPreparedBy = (DropDownList)FormView1.Row.FindControl("dataPreparedBy");
        dataPreparedBy.Enabled = false;
        if (FormView1.CurrentMode == FormViewMode.Insert)
        {
            var txtPaymentDate = (TextBox)FormView1.Row.FindControl("dataPaymentDate");
            var dataExchangeRate = (TextBox)FormView1.Row.FindControl("dataExchangeRate");
            if (string.IsNullOrEmpty(dataExchangeRate.Text))
                dataExchangeRate.Text = WebCommon.SharedFunction.GetVCBHCMExchangeRate();
            //string Perfix = "G" +  DateTime.Now.ToString("yyMMdd");
            //int Count = 0;
            //TList<Grn> objGRN = DataRepository.GrnProvider.GetPaged("GrnId like '" + Perfix + "' + '%'", "GrnId desc", 0, 1, out Count);
            //if (Count == 0)
            //    tbGrnID.Text = Perfix + "-" + "001";
            //else
            //{
            //    tbGrnID.Text = Perfix + "-" + String.Format("{0:000}", int.Parse(objGRN[0].GrnId.Substring((objGRN[0].GrnId.Length - 3))) + 1);
            //}
            if (string.IsNullOrEmpty(txtPaymentDate.Text))
                txtPaymentDate.Text = DateTime.Now.ToString("dd-MMM-yyyy");
            var voidButton = (HtmlControl)FormView1.Row.FindControl("VoidButton");
            voidButton.Style.Add("display", "none");
            var cloneButton = (HtmlControl)FormView1.Row.FindControl("CloneButton");
            cloneButton.Style.Add("display", "none");
            dataPreparedBy.SelectedValue = Context.User.Identity.Name.Split('\\')[1];
            IsEditable = true;
        }
        else
        {
            var dataPaymentTypeId = (EntityDropDownList)FormView1.Row.FindControl("dataPaymentTypeId");
            dataPaymentTypeId.Enabled = false;
            FormView1.FooterRow.FindControl("PreviewButton").Visible = true;
            if (string.IsNullOrEmpty(txt_VoucherDateClone.Text))
                txt_VoucherDateClone.Text = DateTime.Now.ToString("dd-MMM-yyyy");
            var paymentId = Request.QueryString["PaymentId"];
            var objPayment = DataRepository.PaymentProvider.GetByPaymentId(paymentId);
            if (objPayment.IsCompleted || objPayment.PaidDate.HasValue || objPayment.IsVoid)
            {
                FormView1.FooterRow.FindControl("UpdateButton").Visible = false;
                IsEditable = false;
            }
            else
            {
                pn_PaymentDetailsAdd.Visible = true;
                IsEditable = true;
            }
            if (IsEditable == false)
            {
                var voidButton = (HtmlControl)FormView1.Row.FindControl("VoidButton");
                voidButton.Style.Add("display", "none");
            }
        }
    }

    protected void PaymentDataSource_Inserting(object sender, ObjectDataSourceMethodEventArgs e)
    {
        int paymentTypeId = Convert.ToInt32(e.InputParameters["PaymentTypeId"].ToString());
        DateTime paymentDate = Convert.ToDateTime(e.InputParameters["PaymentDate"].ToString());
        var paymentType = DataRepository.PaymentTypeProvider.GetByPaymentTypeId(paymentTypeId);
        int count;
        var payments = DataRepository.PaymentProvider.GetPaged("PaymentId LIKE '" + paymentType.PaymentTypeCode + paymentDate.ToString("yyMM") + "%'",
                                                               "PaymentId DESC", 0, 1, out count);
        string paymentId = "";
        if (count > 0)
        {
            paymentId = paymentType.PaymentTypeCode + paymentDate.ToString("yyMM") +
                        string.Format("{0:000}", int.Parse(payments[0].PaymentId.Substring(7)) + 1);
        }
        else
        {
            paymentId = paymentType.PaymentTypeCode + paymentDate.ToString("yyMM") + "001";
        }
        var obj = new AbAccountCode();
        e.InputParameters["PaymentId"] = paymentId;
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        string whereExpression = string.Format("Accnt_Code='{0}'", dataAccountCode.SelectedValue);
        int count;
        VList<SunAccountCode> accountCodes = DataRepository.SunAccountCodeProvider.GetPaged(whereExpression, "", 0, 1, out count);
        bool error = false;
        var content = (ContentPlaceHolder)this.Master.FindControl("ContentPlaceHolder1");
        div_DetailsError.InnerHtml = "";
        if (string.IsNullOrEmpty(dataAmount.Value))
        {
            div_DetailsError.InnerHtml +=
                @"<div class='notification error png_bg'> <div>Please input Amount</div></div>";
            error = true;
        }
        else
        {
            decimal result;
            if (!decimal.TryParse(dataAmount.Value, out result))
            {
                div_DetailsError.InnerHtml +=
                    @"<div class='notification error png_bg'> <div>Please input valid Amount</div></div>";
                error = true;
            }
        }
        if (string.IsNullOrEmpty(dataAccountCode.SelectedValue))
        {
            div_DetailsError.InnerHtml +=
                @"<div class='notification error png_bg'> <div>Please input Account Code</div></div>";
            error = true;
        }
        else
        {

            for (int i = 0; i < 4; i++)
            {
                if (accountCodes[0].EnterAnal[i] == 'Y')
                {
                    var comboBox = (EntityDropDownList)content.FindControl("dataT" + i.ToString());
                    if (string.IsNullOrEmpty(comboBox.SelectedValue))
                    {
                        div_DetailsError.InnerHtml += @"<div class='notification error png_bg'> <div>Please input T" +
                                                      i.ToString() + "</div></div>";
                        error = true;
                    }
                }
            }
            if (accountCodes[0].EnterAnal[4] == 'Y')
                if (string.IsNullOrEmpty(dataT4.Value))
                {
                    div_DetailsError.InnerHtml +=
                        @"<div class='notification error png_bg'> <div>Please input T4</div></div>";
                    error = true;
                }
            if (accountCodes[0].EnterAnal[5] == 'Y')
                if (string.IsNullOrEmpty(dataT5.Value))
                {
                    div_DetailsError.InnerHtml +=
                        @"<div class='notification error png_bg'> <div>Please input T5</div></div>";
                    error = true;
                }
        }
        if (!error)
        {
            if (btnSave.Text == "Add Detail")
            {
                var paymentDetail = new PaymentDetail
                    {
                        Amount = decimal.Parse(dataAmount.Value),
                        AccountCode = dataAccountCode.SelectedValue.Trim(),
                        MoneyType = dataMoneyType.SelectedValue,
                        PaymentId = Request.QueryString["PaymentId"],
                        DebitCredit = dataDebitCredit.SelectedValue,
                        Description = dataDescription.Text,
                        DescriptionVn = dataDescriptionVN.Text,
                        T0 = dataT0.SelectedValue,
                        T1 = dataT1.SelectedValue,
                        T2 = dataT2.SelectedValue,
                        T3 = dataT3.SelectedValue,
                        T4 = dataT4.Value,
                        T5 = dataT5.Value
                    };
                DataRepository.PaymentDetailProvider.Insert(paymentDetail);
            }
            else if (btnSave.Text == "Update Detail")
            {
                var paymentDetail = (PaymentDetail)Session["PaymentDetail"];
                paymentDetail.Amount = Decimal.Parse(dataAmount.Value);
                paymentDetail.AccountCode = dataAccountCode.SelectedValue;
                paymentDetail.MoneyType = dataMoneyType.SelectedValue;
                paymentDetail.DebitCredit = dataDebitCredit.SelectedValue;
                paymentDetail.Description = dataDescription.Text;
                paymentDetail.DescriptionVn = dataDescriptionVN.Text;
                paymentDetail.T0 = dataT0.SelectedValue;
                paymentDetail.T1 = dataT1.SelectedValue;
                paymentDetail.T2 = dataT2.SelectedValue;
                paymentDetail.T3 = dataT3.SelectedValue;
                paymentDetail.T4 = dataT4.Value;
                paymentDetail.T5 = dataT5.Value;
                DataRepository.PaymentDetailProvider.Update(paymentDetail);
                Session["PaymentDetail"] = null;
            }
            ClearInputForm();
        }
    }

    private void ClearInputForm()
    {
        btnSave.Text = "Add Detail";
        dataAmount.Value = "";
        dataAccountCode.SelectedValue = null;
        dataMoneyType.SelectedValue = "VND";
        dataDebitCredit.SelectedValue = "Debit";
        dataDescription.Text = "";
        dataDescriptionVN.Text = "";
        dataT0.SelectedValue = null;
        dataT1.SelectedValue = null;
        dataT2.SelectedValue = null;
        dataT3.SelectedValue = null;
        dataT4.Value = "";
        dataT5.Value = "";
        GridViewPaymentDetail1.DataBind();
        btnCancel.Visible = false;
        //dataAccountCode.Focus();
    }

    protected void FormView1_ItemCommand(object sender, FormViewCommandEventArgs e)
    {
        if (e.CommandName == "Print")
        {
            var paymentId = Request.QueryString["PaymentId"];
            var payment = DataRepository.PaymentProvider.GetByPaymentId(paymentId);
            var listPayment = new TList<Payment> { payment };
            Session["Payment"] = listPayment;
            Response.Redirect("ReportPaymentVoucher.aspx", true);
        }
    }

    protected void btnVoid_Click(object sender, EventArgs e)
    {
        var paymentId = Request.QueryString["PaymentId"];
        VoidPayment(paymentId, dataVoidReason.Text);
    }

    private void VoidPayment(string paymentId, string voidReason)
    {
        var payment = DataRepository.PaymentProvider.GetByPaymentId(paymentId);
        DataRepository.PaymentProvider.DeepLoad(payment);
        var paymentAccount = DataRepository.PaymentAccountProvider.GetByPaymentAccount(payment.PaymentTypeIdSource.AccountNumber);
        if (paymentAccount != null)
        {
            var amount = payment.Amount;
            if (payment.IsDebit.Value)
                amount *= -1;
            paymentAccount.CurrentBalance += amount;
            DataRepository.PaymentAccountProvider.Update(paymentAccount);
        }
        payment.IsVoid = true;
        payment.VoidBy = Context.User.Identity.Name.Split('\\')[1];
        payment.VoidDate = DateTime.Now;
        payment.VoidReason = voidReason;
        payment.IsCompleted = true;
        DataRepository.PaymentProvider.Update(payment);
    }
    protected void GridViewPaymentDetail1_DataBound(object sender, EventArgs e)
    {
        //Calculate Amount in footer row
        if (GridViewPaymentDetail1.Rows.Count > 0)
        {
            Decimal totalAmount = 0;
            foreach (GridViewRow dataRow in GridViewPaymentDetail1.Rows)
            {
                var value = decimal.Parse(dataRow.Cells[4].Text);
                if (dataRow.Cells[5].Text == "Debit")
                    totalAmount -= decimal.Parse(dataRow.Cells[4].Text);
                else
                    totalAmount += decimal.Parse(dataRow.Cells[4].Text);
            }
            GridViewPaymentDetail1.FooterRow.Cells[4].Text = String.Format("{0:#,0.00}", totalAmount);
        }
    }

    protected void GridViewPaymentDetail1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "DetailEdit")
        {
            btnSave.Text = "Update Detail";
            btnCancel.Visible = true;
            var paymentDetailId = Int32.Parse(e.CommandArgument.ToString());
            var paymentDetail = DataRepository.PaymentDetailProvider.GetByPaymentDetailId(paymentDetailId);
            dataAmount.Value = paymentDetail.Amount.ToString();
            dataAccountCode.SelectedValue = paymentDetail.AccountCode;
            dataMoneyType.SelectedValue = paymentDetail.MoneyType;
            dataDebitCredit.SelectedValue = paymentDetail.DebitCredit;
            dataDescription.Text = paymentDetail.Description;
            dataDescriptionVN.Text = paymentDetail.DescriptionVn;
            dataT0.SelectedValue = paymentDetail.T0;
            dataT1.SelectedValue = paymentDetail.T1;
            dataT2.SelectedValue = paymentDetail.T2;
            dataT3.SelectedValue = paymentDetail.T3;
            dataT4.Value = paymentDetail.T4;
            dataT5.Value = paymentDetail.T5;
            Session["PaymentDetail"] = paymentDetail;
            dataAccountCode.Focus();
        }
        else if (e.CommandName == "Clone")
        {
            btnCancel.Visible = true;
            var paymentDetailId = Int32.Parse(e.CommandArgument.ToString());
            var paymentDetail = DataRepository.PaymentDetailProvider.GetByPaymentDetailId(paymentDetailId);
            dataAmount.Value = paymentDetail.Amount.ToString();
            dataAccountCode.SelectedValue = paymentDetail.AccountCode;
            dataMoneyType.SelectedValue = paymentDetail.MoneyType;
            dataDebitCredit.SelectedValue = paymentDetail.DebitCredit;
            dataDescription.Text = paymentDetail.Description;
            dataDescriptionVN.Text = paymentDetail.DescriptionVn;
            dataT0.SelectedValue = paymentDetail.T0;
            dataT1.SelectedValue = paymentDetail.T1;
            dataT2.SelectedValue = paymentDetail.T2;
            dataT3.SelectedValue = paymentDetail.T3;
            dataT4.Value = paymentDetail.T4;
            dataT5.Value = paymentDetail.T5;
            dataAccountCode.Focus();
        }
    }

    protected void btnCancel_Click(object sender, EventArgs e)
    {
        ClearInputForm();
    }

    protected void GridViewPaymentDetail1_SelectedIndexChanged(object sender, EventArgs e)
    {
        throw new NotImplementedException();
    }

    protected void btnClone_Click(object sender, EventArgs e)
    {
        string paymentId = Request.QueryString["PaymentId"];
        var clonePayment = DataRepository.PaymentProvider.GetByPaymentId(paymentId);
        var paymentDate = DateTime.Parse(txt_VoucherDateClone.Text);
        DataRepository.PaymentProvider.DeepLoad(clonePayment);
        int count;
        var payments = DataRepository.PaymentProvider.GetPaged("PaymentId LIKE '" + clonePayment.PaymentTypeIdSource.PaymentTypeCode + paymentDate.ToString("yyMM") + "%'",
                                                           "PaymentId DESC", 0, 1, out count);
        if (count > 0)
        {
            paymentId = clonePayment.PaymentTypeIdSource.PaymentTypeCode + paymentDate.ToString("yyMM") +
                        string.Format("{0:000}", int.Parse(payments[0].PaymentId.Substring(7)) + 1);
        }
        else
        {
            paymentId = clonePayment.PaymentTypeIdSource.PaymentTypeCode + paymentDate.ToString("yyMM") + "001";
        }
        clonePayment.PaymentDate = paymentDate;
        clonePayment.PaymentId = paymentId;
        clonePayment.IsNew = true;
        clonePayment.PreparedBy = Context.User.Identity.Name.Split('\\')[1];
        clonePayment.IsCompleted = false;
        clonePayment.ExportedDate = null;
        clonePayment.PaidDate = null;
        clonePayment.PaidBy = null;
        clonePayment.ExportedBy = null;
        clonePayment.OpenBalance = 0;
        clonePayment.IsVoid = false;
        clonePayment.VoidBy = null;
        clonePayment.VoidDate = null;
        DataRepository.PaymentProvider.Insert(clonePayment);
        foreach (var detail in clonePayment.PaymentDetailCollection)
        {
            detail.PaymentId = paymentId;
            detail.IsNew = true;
            DataRepository.PaymentDetailProvider.Insert(detail);
        }
        Response.Redirect("PaymentEdit.aspx?PaymentId=" + paymentId + "&Message=CloneSuccess", true);
    }
}